package s;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.LockObtainFailedException;

import net.semanticmetadata.lire.DocumentBuilder;
import net.semanticmetadata.lire.DocumentBuilderFactory;

import cbir.MyFileFilter;
import cbir.Thumb;

import com.mysql.jdbc.Statement;

public class RemoveImg extends HttpServlet{

		private static final long serialVersionUID = 1L;
		private Properties props;
		private String propsPath;
		
		
		@Override
		public void init(ServletConfig config) throws ServletException {
			super.init(config);
			
			this.propsPath = this.getServletContext().getRealPath("/");
			this.props = new Properties();
			try {
				props.loadFromXML(new FileInputStream(propsPath + "properties.properties"));
			} catch (FileNotFoundException e) {e.printStackTrace();} 
			catch (IOException e) {e.printStackTrace();}
		}
		
		@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse res)	throws ServletException, IOException {
				exe(req,res);
		}	
		
		@SuppressWarnings("deprecation")
		private synchronized void exe(HttpServletRequest req, HttpServletResponse res) throws CorruptIndexException, LockObtainFailedException, IOException{
				String filename = req.getParameter("filename");
				// 1. 
				// Modify MySQL
				
				Connection connection = null;
				try {
					Class.forName("com.mysql.jdbc.Driver");
					connection = DriverManager.getConnection(props.getProperty("DB_URL"), props.getProperty("DB_USER"), props.getProperty("DB_PASS"));
					Statement statement = (Statement) connection.createStatement();
					statement.executeUpdate("DELETE FROM imgTag WHERE IdImg = (SELECT IdImg FROM img WHERE Filename = '" + filename + "') ;");
					statement.executeUpdate("DELETE FROM img WHERE Filename = '" + filename + "' ;");
				}
				catch (SQLException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}
				
				// 2.
				// Remove files
				
				File img = new File(this.getServletContext().getRealPath("/") + props.getProperty("IMG_PATH") + filename);
				File thumb = new File(this.getServletContext().getRealPath("/") + props.getProperty("IMG_PATH") + "thumb/" + Thumb.getThumb(filename));
				if(img.delete() == false)
					System.err.println("Fail while removing the file");
				if(thumb.delete() == false)
					System.err.println("Fail while removing the file");
				
				// 3.
				// Indexing
				
				DocumentBuilder builder = DocumentBuilderFactory.getExtensiveDocumentBuilder();
				IndexWriter iw = new IndexWriter(this.getServletContext().getRealPath("/") + props.getProperty("INDEX_PATH"), new SimpleAnalyzer(), true);
				Document doc = null;
				File dir = new File(this.getServletContext().getRealPath("/") +  props.getProperty("IMG_PATH") + "thumb/");
				File[] fileList = dir.listFiles(new MyFileFilter());
				for(int i = 0; i < fileList.length; i++){
					if(fileList[i].isDirectory() == false){
						doc = builder.createDocument(new FileInputStream(fileList[i]), fileList[i].getName());
						iw.addDocument(doc);
					}
				}
				iw.optimize();
				iw.close();
				
				PrintWriter pw = res.getWriter();
				pw.print("OK");
			
		}
}